package com.example.springdemo.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.util.FileUtil;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 解析eureka服务地址
 *
 * @author pengzhikang
 * @date 2023/3/24 14:48
 * @since 1.0.0
 */
@Slf4j
public class EurekaApps {

    public void getEurekaSerice() throws Exception {
        InputStream inputStream = this.getClass().getResourceAsStream("apps.json");
        byte[] content = FileUtil.readAsByteArray(inputStream);

        Map<String, Object> vars = new HashMap<>();

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode docmentJson = objectMapper.readTree(content);
        JsonNode applications = docmentJson.get("applications").get("application");
        for (int i = 0; i < applications.size(); i++) {
            JsonNode application = applications.get(i);
            JsonNode name = application.get("name");
            JsonNode instances = application.get("instance");

            String applicationName = name.textValue();
            String ipAddress = null;
            int port = 0;
            if (instances.size() > 1) {
                for (JsonNode instance : instances) {
                    String _instanceId = instance.get("instanceId").textValue();
                    String _ipaddress = instance.get("ipAddr").textValue();
                    if (_instanceId.startsWith(_ipaddress)) {
                        ipAddress = _ipaddress;
                        port = instances.get(0).get("port").get("$").intValue();
                    }
                }
            } else {
                ipAddress = instances.get(0).get("ipAddr").textValue();
                port = instances.get(0).get("port").get("$").intValue();
            }
            // log.info("{}= {}:{}", applicationName, ipAddress, port);
            vars.put(applicationName, String.format("{\"ipAddr\":\"%s\",\"port\":%d}", ipAddress, port));
        }

        log.info("{}", vars);
    }

    public static void main(String[] args) throws Exception {
        new EurekaApps().getEurekaSerice();
    }
}
